<template>
  <view class="home" style="min-height: calc(100vh - 100rpx)">
    <offline-banner
      v-if="activited"
      ref="offline"
      :top="0"
      @refresh="refreshData"
    ></offline-banner> 
    <view class="content">
      <nav-index
        :loadNum="loadNum"
        v-if="footerKey == 'home' && userinfo.user_id"
        :bottom="safeAreaBottom"
        @changeTab="toAaciveTab"
        :is-refresh="isRefresh"
        ref="homeIndex"
        :scrollTop="scrollTop"
      ></nav-index>
      
      <my-task
        v-if="footerKey == 'myTask'"
        ref="myTask"
        :scrollTop="scrollTop"
        :overShow="overShow"
      ></my-task>
      <address-book
        v-if="footerKey == 'addressBook'"
        ref="addressBook"
      ></address-book>
      <personal-center
        v-if="footerKey == 'personalCenter'"
        :bottom="safeAreaBottom"
		@getMsgCount="getMsgCount"
      ></personal-center>
    </view>

    <!-- <tab-bar></tab-bar> -->
    <!-- tabbar部分 -->
    <view
      class="footer"
      :style="paddingBottom ? 'padding-bottom:' + safeAreaBottom + 'px' : ''"
    >
      <view
        class="box"
        v-for="(item, index) in footerList"
        :key="index"
        @click="changeTab(item, index)"
      >
        <view
          :class="[item.key == 'add' ? 'addItem' : 'footer_item']"
          v-if="(findRoute(item.route) && onlineStatus)"
          :style="{ width: `${750 / routeArr.length}rpx` }"
        >
          <image
            :src="item.key == footerKey ? item.activeIcon : item.icon"
            mode=""
            :class="[item.key == 'add' ? 'addImg' : '']"
          ></image>

          <view :class="[item.key == footerKey ? 'active' : '']">{{
            item.name
          }}</view>
        </view>
        <view class="dot" v-if="item.key == 'personalCenter'&&unreadMsg>0"></view>
      </view>
    </view>
    <!-- 新增弹出框 -->
    <uni-popup
      ref="popup3"
      type="bottom"
      :mask-click="true"
      background-color="#fff"
      @change="changePopup"
    >
      <view class="addContent">
        <view class="taskBox">
          <view
            v-for="(item, index) in orderTask"
            :key="index"
            class="box_content"
          >
            <view
              @click="toTaskApprove(item.id)"
              v-if="findRoute(item.route)||item.route=='add_rescue'"
              class="taskBox_item"
            >
              <image :src="item.icon" mode="" />
              <view class="name">{{ item.name }}</view>
            </view>
          </view>
        </view>

        <view
          class="bottom"
          @click="closePopup"
          :style="{
            paddingBottom: safeAreaBottom + 'px',
          }"
          >取消</view
        >
      </view>
    </uni-popup>

    <image
      class="camera_index"
      src="@/static/images/camera_index.png"
      mode=""
      @click="toCamera"
    ></image>
  </view>
</template>

<script>
import offlineBlock from '@/components/offline-block/offline-block.vue';
import { mapState, mapActions } from 'vuex';
import NavIndex from './components/nav_bar/index.vue';
import MyTask from '@/subpages/myTask/index.vue';
import AddressBook from '@/subpages/addressBook/index.vue';
import PersonalCenter from '@/subpages/personalCenter/index.vue';
import { getUnreadCount, getUserMsgPage } from '@/apis/notice.js';

import { hanleToken,uniqueArr } from '@/utils/utils.js';

export default {
	components: {
		offlineBlock, 
		NavIndex,
		MyTask,
		AddressBook,
		PersonalCenter,
		
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	data() {
		return {
			activited: true,
			overflowShow: false,
			loadNum: 1,
			// 滚动距离
			scrollTop: 0,

			// 新建工单类型
			orderTask: [
				{
					name: '配件申请',
					icon: '/static/navbar/pj.png',
					route: 'add_parts',
					id: 1,
				},
				{
					name: '故障报修',
					icon: '/static/navbar/gz.png',
					route: 'add_malfunction',
					id: 0,
				}
			],
			footerList: [
				{
					name: '首页',
					icon: '/static/navbar/index_nor.png',
					activeIcon: '/static/navbar/index_hl.png',
					url: '/pages/home/index',
					route: 'maintain_home',
					key: 'home',
				},

				{
					name: '我的任务',
					icon: '/static/navbar/order_nor.png',
					activeIcon: '/static/navbar/order_hl.png',
					url: '/pages/myTask/index',
					route: 'maintain_home',
					key: 'myTask',
				},
				// 新建维修
				{
					name: '新增',
					icon: '/static/navbar/add.png',
					activeIcon: '/static/navbar/add.png',
					//   url: "/pages/myTask/index",
					route: 'maintain_add',
					key: 'add',
					size: '88rpx',
				},
			 
				{
					name: '通讯录',
					icon: '/static/navbar/address_nor.png',
					activeIcon: '/static/navbar/address_hl.png',
					url: '/pages/addressBook/index',
					route: 'maintain_dept_address_list',
					key: 'addressBook',
				},
				{
					name: '个人中心',
					icon: '/static/navbar/mine_nor2.png',
					activeIcon: '/static/navbar/mine_hl.png',
					url: '/subpages/personalCenter/index',
					route: 'maintain_personal_center',
					key: 'personalCenter',
				},
			],
			footerIndex: '',
			paddingBottom: null,
			safeAreaBottom: 40,
			isRefresh: false,
			offTimer: null,
			footerKey: 'home',
			// 获取加载多少个底部tab
			routeArr: [],
			// 模版消息跳进去事务工单 1保养2维修3救援4配件5事务
			typeStatus: '',
			// 未读信息
			unreadMsg: 0,
			// myTask refs 检查定时器
			myTaskCheckTimer: null,
			
		};
	},
	computed: {
		// 离线状态 ture 在线
		...mapState('system', ['onlineStatus']),
		...mapState('user', ['userinfo', 'routes']),
		height() {
			return 'calc(100vh - 100rpx)';
		},
	},
	watch: {
		onlineStatus(val) {
			if (
				val &&
        this.activited &&
        this.userinfo.user_id &&
        this.$refs.offline
			) {
				// 网络状态更变离线 获取本地详情
				this.$refs.offline.changeStatus();
			}
		},
		footerIndex(val, old) {
			console.log(val, old, '看看角标');
			this.getUnreadMsg();
		},
	},

	async onShow() {
		this.activited = true;
		uni.setStorageSync('newTop', 0);
		let hasLogin = await this.handleRreshToken();
		const token = hanleToken('get', 'refresh_token');
		if (!token) {
			console.log('this.toLogin();');
			this.toLogin();
			return;
		}
		if ((!hasLogin || !this.userinfo || !this.userinfo.user_id) && this.onlineStatus) {
			console.log('this.toLogin();');
			this.toLogin();
			return;
		}
		// 初始化路由权限
		if (!this.routes || this.routes.length == 0) {
			console.log('加载路由权限1');
			await this.getRoutes();
			// 加载底部栏的数量
			this.routeArr = this.footerList.filter((item) => {
				return this.findRoute(item.route);
			});
			console.log(this.routeArr, 999);
		}
		getApp().globalData.userinfo = this.userinfo;
		// 首页
		if (this.footerKey == 'home') {
			this.$refs.homeIndex.initData();
		}
		console.log(this.footerKey,'this.footerKey');
		// 我的任务
		if (this.footerKey == 'myTask') {
			// console.log('返回刷新',this.$refs.myTask);
			this.$nextTick(()=>{
				if (this.$refs.myTask) {
					this.$refs.myTask.getLocationFun();
				}
			});
		}
		this.setOffTimer();
	},
	async onLoad(e) { 
		// #ifdef MP-WEIXIN
		uni.getSystemInfo({
			success: (res) => {
				// 增加底部边距
				this.paddingBottom = true;
				this.safeAreaBottom = res.screenHeight - res.safeArea.bottom;
			},
		});
		// #endif
		// 去到那个tabbar
		// 判断去到哪个工单类型
		if (e.typeStatus) {
			this.typeStatus = e.typeStatus;
		}
		if (e.footerKey) {
			this.footerKey = e.footerKey;
			let i = this.orderTask.findIndex((item) => {
				item.key == e.footerKey;
			});
			this.footerIndex = i;
			if (e.footerKey == 'myTask') {
				console.log('我的工单');
				if (e.typeStatus) {
					this.$nextTick(() => {
						this.$refs.myTask.getCate(e.typeStatus);
					});
				}
			}
		} else {
			this.footerIndex = 0;
			this.footerKey = 'home';
			// this.footerKey = 'myTask';
		}

		// #ifdef H5
		const vm = this;
		setTimeout(function () {
			uni.$on('switchTab', (index, rescue) => {
				console.log(`switchTab : index:${index} rescue:${rescue}`);
				vm.changeTab({ ...vm.footerList[index], rescue }, index);
			});

			uni.$on('loadNum', () => {
				vm.loadNum--;
			});
		}, 500);
		// #endif

		// #ifndef H5
		uni.$on('switchTab', (index, rescue) => {
			this.changeTab({ ...this.footerList[index], rescue }, index);
		});

		uni.$on('loadNum', () => {
			this.loadNum--;
		});
		// #endif
		// 获取维修工单列表
		setTimeout(() => {
			this.setCircularFence();
		}, 2000);
	},
	onHide() {
		this.activited = false;
		if (this.offTimer) {
			clearInterval(this.offTimer);
			this.offTimer = null;
		}
		// 清理 myTask refs 检查定时器
		if (this.myTaskCheckTimer) {
			clearInterval(this.myTaskCheckTimer);
			this.myTaskCheckTimer = null;
		}
		// 关闭对应组件定时器
		if (this.footerKey == 'myTask') {
			this.$refs.myTask.closeTimer();
			// 关闭维修子组件定时器
			uni.$emit('myTaskHide');
		}
	},
	onUnload() {
		if (this.offTimer) {
			clearInterval(this.offTimer);
			this.offTimer = null;
		}
		// 清理 myTask refs 检查定时器
		if (this.myTaskCheckTimer) {
			clearInterval(this.myTaskCheckTimer);
			this.myTaskCheckTimer = null;
		}
		// 关闭对应组件定时器
		if (this.footerKey == 'myTask') {
			this.$refs.myTask.closeTimer();
		}
	},
	beforeDestroy() {
		uni.$off('switchTab');
		uni.$off('loadNum');
		uni.$off('myTaskHide');
	},

	methods: {
		...mapActions('user', ['handleRreshToken', 'getRoutes']),
		// 检查 myTask refs 是否存在
		checkMyTaskRefs(item) {
			// 清除之前的定时器
			if (this.myTaskCheckTimer) {
				clearInterval(this.myTaskCheckTimer);
				this.myTaskCheckTimer = null;
			}
			
			// 安全地检查 refs 是否存在
			if (this.isMyTaskRefsAvailable()) {
				// refs 存在，清除 loading
			
				console.log('myTask refs 已获取到检查');
				this.$refs.myTask.getLocationFun(item.rescue);
				this.$refs.myTask.initTimer();// 开启维修时间标签定时器
				uni.hideLoading();
				return;
			}
			
			// refs 不存在，启动定时器检查
			// 每100ms检查一次
			this.myTaskCheckTimer = setInterval(() => {
				if (this.isMyTaskRefsAvailable()) {
					// refs 存在，清除定时器和 loading
					clearInterval(this.myTaskCheckTimer);
					this.myTaskCheckTimer = null;
					
					this.$refs.myTask.getLocationFun(item.rescue);
					this.$refs.myTask.initTimer();// 开启维修时间标签定时器
					console.log('myTask refs 已获取到定时器里面');
					uni.hideLoading();
				}
			}, 100);
		},
		
		// 安全地检查 myTask refs 是否可用
		isMyTaskRefsAvailable() {
			try {
				// 先检查 refs 对象是否存在
				if (!this.$refs) {
					return false;
				}
				
				// 检查 myTask refs 是否存在且不为 null
				const myTaskRef = this.$refs.myTask;
				return myTaskRef && myTaskRef !== null && typeof myTaskRef === 'object';
			} catch (error) {
				console.log('检查 myTask refs 时出错:', error);
				return false;
			}
		},
		getMsgCount(res) {
			this.unreadMsg = res;
		},
		async getUnreadMsg() {
			// 查询未读信息
			try {
				const res = await getUnreadCount();
				const res2 = await getUserMsgPage({current: 1, size: 10, typeId: 14, status: 1});
				let count = 0;
				console.log(res, 'res');
				console.log(res2, 'getUserMsgPage');
				if (res && res.code === 200) {
					count += res.data;
				}
				if (res2 && res2.code === 200) {
					count += res2.data.total;
				}
				this.unreadMsg = count;
			} catch (error) {
				console.log(error);
			}
		},
		toCamera() {
			uni.navigateTo({
				url: '/pages/camera/camera?justPhoto=true',
				fail: (err) => {
					console.log(err);
				},
			});
		},
		setOffTimer() {
			// 定时同步离线签到定时器
			if (this.offTimer) {
				clearInterval(this.offTimer);
			}
			this.offTimer = setInterval(() => {
				// console.log('定时同步-首页与列表')
				try {
					if (this.footerKey == 'home') {
						this.$refs.homeIndex.postOffLineRecord();
					}
					if (this.footerKey == 'myTask') {
						this.$refs.myTask.postOffLineRecord();
					}
				} catch (err) {}
			}, 10000);
		},
		relantchfuc() {
			uni.reLaunch({
				url: '/pages/home/index',
			});
		},
		refreshData() {
			this.changeTab(this.footerList[this.footerIndex], this.footerIndex);
		},
		// 点击tabbar
		changeTab(item, index) {
			console.log('changeTab:', item, 999, ' index:', index);
			if (item.key == 'add') {
				this.$refs.popup3.open();
				return;
			}
			this.footerIndex = index;
			this.footerKey = item.key;
			uni.setNavigationBarTitle({
				title: item.key == 'home' ? '梯无忧' : item.name,
			});
			uni.pageScrollTo({
				scrollTop: 0,
			});

			this.$nextTick(() => {
				// console.log('点击底部按钮');
				if (this.footerKey == 'home') {
					// this.isRefresh=true
					this.$refs.homeIndex.initData();
				}
				if (this.footerKey == 'myTask') {
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					
					// 检查 myTask refs 是否存在
					this.checkMyTaskRefs(item);
				}
			});
		},
		async fetchCardData() {
			let requestFunList = this.cardRoteList.filter((item, index) => {
				return this.findRoute(item.route) == true;
			});
			uni.showLoading({
				title: '加载中',
				icon: 'loadding',
				mark: true  
			});
			let all = requestFunList.map((e) => {
				return e.fun;
			});
			console.log(requestFunList, all);
			await Promise.all(all).then((res) => {
				uni.hideLoading();
				requestFunList.forEach((v, index) => {
					this.cardRoteList.forEach((j) => {
						if (v.name == j.name) {
							this.$set(j, 'data', res[index].data);
						}
					});
				});
				// console.log(this.cardRoteList[1].data,999);
			});
		},
		toLogin() {
			uni.navigateTo({
				url: '../login/index',
			});
		},
		toAaciveTab(res) {
			console.log(res, 'toAaciveTab');
			this.footerIndex = res;
		},
		// changeRole() {
		// 	uni.navigateTo({
		// 		url: '/pages/login/companySelect'
		// 	});
		// },
		// 点击弹出框任务选项
		toTaskApprove(id) {
			this.toDisabilities(id);
		},
		// 去选择楼盘//分故障页和申请配件页面
		toDisabilities(index) {
			if (index == 2) {
				uni.navigateTo({
					url: '/subpages/rescue/projectSelect',
				});
				this.closePopup();
				return;
			}
			let type = index;
			let url = '/pageModules/barrierSearch/searchBg?type=' + type;
			if (this.findRoute('add_parts_multiple') && type == 1) {
				type = 1;
				url += '&multiSelect=true';
			}
			// 0为故障报修,1为配件申请
			uni.navigateTo({
				url: url,
			});
			this.closePopup();
		},
		changePopup(res) {
			// console.log(res);
		},
		closePopup() {
			this.$refs.popup3.close();
		},
		overShow(status) {
			this.overflowShow = status;
		},
		// 获取维修工单列表 创建电子围栏
		async setCircularFence() {
			// 检查 window.sida 是否存在
			let resArr = [],arrs = [],uArrs = [];
			try {
				resArr = await this.$store.dispatch('user/getPlanLatitude');
				uArrs = uniqueArr(resArr, 'buildingId');
				arrs = uArrs.map((item) => {
					return {
						radius: item.planSignM,
						latitude: parseFloat(item.latitude),
						longitude: parseFloat(item.longitude),
						id: `${item.planId}|${item.buildingId}|${item.elevatorId}-${item.buildingPlanCounts}-${item.signType}`
					};
				});
			} catch (err) {
				console.log('错误err',err);
			}

			// #ifdef H5
			if (window.sida) {
				window.sida.setCircularFence({
					data: arrs,
					success: function(result) {
						console.log('围栏设置成功1');
					},
					fail: function(err) {
						console.log('围栏设置失败2:', err);
					}
				});
			} else {
				console.error('sida 包未加载，请确保已引入 sida 相关脚本');
			}
			// #endif
		},
	},
};
</script>

<style lang="scss" scoped>
.addContent {
  // height: 600rpx;
  background: #fff;
  border-radius: 8rpx 8rpx 0rpx 0rpx;
  box-shadow: 0rpx -4rpx 12rpx 0rpx rgba(0, 0, 0, 0.12);

  .taskBox {
    display: flex;
    padding: 48rpx 40rpx;

    .box_content {
      display: flex;
       flex:1
    }
  }

  .taskBox_item {
    display: flex;
    flex: 1;
    flex-direction: column;
    // flex: 1
    // height: 300rpx;
    align-items: center;
    justify-content: center;

    image {
      width: 96rpx;
      height: 96rpx;
    }

    .name {
      font-size: 24rpx;
      color: #333;
    }
  }

  .bottom {
    height: 98rpx;
    display: flex;
    color: #666666;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
  }
}

.home {
  background: #f3f6f8;
  min-height: 100vh;
  padding-bottom: 100rpx;

  .header {
    display: flex;
    font-size: 24rpx;
    height: 74rpx;
    padding: 8rpx 20rpx;
    justify-content: space-between;
    background-color: #2c2c2c;
    color: #fff;
    box-sizing: border-box;
    align-items: center;
    position: sticky;
    top: 0;
    left: 0;

    .header_left,
    .header_right {
      display: flex;
    }

    .header_left {
      image {
        width: 64rpx;
        height: 64rpx;
        margin-right: 12rpx;
        border-radius: 50%;
      }

      .infoName {
        display: flex;
        align-items: center;
        flex: 1;

        text {
          border-radius: 4rpx;
          font-size: 22rpx;
          padding: 4rpx 8rpx;
          margin-left: 16rpx;
          margin-top: 6rpx;
        }

        .nickName {
          font-size: 26rpx;
          font-weight: 600;
          color: #ffffff;
        }
      }
    }

    .header_right {
      width: 200rpx;
      display: flex;
      align-items: center;
      height: 100%;
      justify-content: flex-end;

      image {
        width: 32rpx;
        height: 32rpx;
        margin-right: 4rpx;
      }
    }
  }

  .cardContent {
    padding: 8rpx 20rpx 0 20rpx;
    margin-bottom: 78rpx;

    .cardItem {
      background-color: #fff;
      border-radius: 8rpx;
      margin: 16rpx 0;

      .header {
        display: flex;
        justify-content: space-between;
        padding: 18rpx 32rpx 16rpx 32rpx;
        align-items: center;
        border-bottom: 2rpx solid #eeeeee;

        .header_left {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
          display: flex;

          image {
            margin-right: 12rpx;
            width: 48rpx;
            height: 48rpx;
          }
        }
      }

      .main {
        .main_item {
          padding: 32rpx 32rpx 22rpx 0rpx;

          .title {
            border-left: 4rpx solid #0091ff;
            padding-left: 32rpx;
            margin-bottom: 16rpx;
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
          }
        }

        .subMain {
          padding-left: 32rpx;
          display: flex;

          .subMain_item {
            display: flex;
            flex: 1;
            align-items: center;
            flex-direction: column;
            border-right: 2rpx solid #eeeeee;

            .count {
              color: #333;
              font-size: 32rpx;
              font-weight: 600;
            }

            .bottom {
              font-size: 24rpx;
              color: #666;
            }
          }

          &:nth-last-child(1) {
            border-right: none;
          }
        }
      }
    }
  }

  .guarantee {
    // height: 80rpx;
    padding: 18rpx 20rpx 16rpx 32rpx;
    background: #ffffff;
    border-radius: 8rpx;
    box-shadow: 0rpx 2rpx 8rpx 6rpx rgba(30, 67, 95, 0.08);
    margin: 0 20rpx;
    display: flex;
    justify-content: space-between;
    position: fixed;
    bottom: 120rpx;
    left: 0;
    width: 710rpx;
    box-sizing: border-box;

    image {
      width: 48rpx;
      height: 48rpx;
      margin-right: 12rpx;
    }

    .title {
      display: flex;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .btn {
      width: 156rpx;
      background: #0091ff;
      border-radius: 4rpx;
      color: #fff;
      height: 52rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
    }
  }

  .footer {
    display: flex;
    height: 98rpx;
    background-color: #fff;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 100;
    border-top: 2rpx solid #e9e9e9;
    justify-content: space-around;

    /* #ifdef H5 */
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    /* #endif */

    image {
      width: 48rpx;
      height: 48rpx;
    }

    .box {
      position: relative;
    }

    .footer_item {
      display: flex;
      flex: 1;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #999;
      font-size: 20rpx;
      width: 150rpx;
      height: 100%;

      .addImg {
        width: 88rpx;
        height: 88rpx;
      }
    }
    .dot {
      width: 10rpx;
      height: 10rpx;
      background: red;
      border-radius: 50%;
      position: absolute;
      top: 10px;
      right: 17px;
      z-index: 10;
    }

    .addItem {
      position: relative;
      top: -26rpx;
      display: flex;
      color: #999;
      font-size: 20rpx;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 114rpx;

      view {
        text-align: center;
      }

      image {
        width: 88rpx;
        height: 88rpx;
      }
    }

    .active {
      color: #0091ff;
    }
  }
}

.camera_index {
  position: fixed;
  bottom: 330rpx;
  right: 20rpx;
  z-index: 10;
  width: 80rpx;
  height: 80rpx;
}
</style>
